﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Web;

/// <summary>
/// 页面基类
/// </summary>
public class PageBase : System.Web.UI.Page
{
    protected  string Lang = "zh-CN";

    /// <summary>
    /// 重写用户区域和语言区域初始化信息
    /// </summary>
    protected override void InitializeCulture()
    {
        //从基类获取语言和区域信息
        base.InitializeCulture();

        //获取用户提交的语言区域
        string LanguagePreference = Request["lang"] != null ? Request["lang"] : null;

        //如果不为空更新Cookie语言区域设置
        if (!string.IsNullOrWhiteSpace(LanguagePreference))
        {
            HttpCookie cookie = 
                new HttpCookie("lang", LanguagePreference);
            cookie.Expires = DateTime.MaxValue;
            Response.Cookies.Add(cookie);
        }
        //从浏览器默认语言区域设置中读取
        else
        {
            LanguagePreference =
                Request.UserLanguages != null ? Request.UserLanguages.First() : null;
            //将语言区域设置保存至Cookie
            if (!string.IsNullOrWhiteSpace(LanguagePreference))
            {
                HttpCookie cookie = new HttpCookie("lang", LanguagePreference);
                cookie.Expires = DateTime.MaxValue;
                Response.Cookies.Add(cookie);
            }
        }

        //语言区域设置不为空
        if (!string.IsNullOrWhiteSpace(LanguagePreference))
        {
            //更新服务端语言区域设置
            try
            {
                Thread.CurrentThread.CurrentUICulture =
                    CultureInfo.CreateSpecificCulture(LanguagePreference);
                Thread.CurrentThread.CurrentCulture =
                    CultureInfo.CreateSpecificCulture(LanguagePreference);
            }
            //如果区域设置不正常
            catch
            {
                //将当前服务器默认语言设置写入Cookie语言区域设置
                HttpCookie cookie = 
                new HttpCookie("lang", Thread.CurrentThread.CurrentUICulture.ToString());
                cookie.Expires = DateTime.MaxValue;
                Response.Cookies.Add(cookie);
            }

        }
        else
        {
            //将当前服务器默认语言设置写入Cookie语言区域设置
            HttpCookie cookie = 
                new HttpCookie("lang", Thread.CurrentThread.CurrentUICulture.ToString());
            cookie.Expires = DateTime.MaxValue;
            Response.Cookies.Add(cookie);
        }

        //注册线程语言特性
        this.Lang = Thread.CurrentThread.CurrentUICulture.Name;
    }

}